package com.sync.syncmasterdata.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 转换 工具
 */
public class ConvertUtil {
    /**
     * 转换对象用 根据map key放目标类字段,value放源类字段
     * @param map
     * @param t
     * @param destinationClass
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T convertClass(Map<String, String> map, Object t, Class<?> destinationClass) throws Exception {
        Object obj = destinationClass.newInstance();
        Class sourceClass = t.getClass();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            Method sourceMethod = sourceClass.getDeclaredMethod("get" + entry.getValue().substring(0, 1).toUpperCase() + entry.getValue().substring(1));
            Field destinationField = destinationClass.getDeclaredField(entry.getKey());
            Class<?> fieldTypeClass = destinationField.getType();
            Object value = convertValType(sourceMethod.invoke(t), fieldTypeClass);
            destinationClass.getMethod("set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1), fieldTypeClass).invoke(obj, value);
        }
        return (T) obj;
    }

    /**
     * 强转为目标类型的方法,如果强转失败,抛异常
     *
     * @param value
     * @param fieldTypeClass
     * @return
     */
    private static Object convertValType(Object value, Class<?> fieldTypeClass) {
        Object retVal = null;
        if (Long.class.getName().equals(fieldTypeClass.getName())
                || long.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Long.parseLong(value.toString());
        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
                || int.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Integer.parseInt(value.toString());
        } else if (Float.class.getName().equals(fieldTypeClass.getName())
                || float.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Float.parseFloat(value.toString());
        } else if (Double.class.getName().equals(fieldTypeClass.getName())
                || double.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Double.parseDouble(value.toString());
        }else if (String.class.getName().equals(fieldTypeClass.getName())){
            retVal = String.valueOf(value);
        } else {
            retVal = value;
        }
        return retVal;
    }

    public static String addOaRequestHeader(String str){
        StringBuilder sb = new StringBuilder();
        sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:mod=\"http://localhost/services/ModeDateService\"> <soapenv:Header/> <soapenv:Body> <mod:saveModeData>  <mod:in0>");
        sb.append(str);
        sb.append("</mod:in0> </mod:saveModeData> </soapenv:Body> </soapenv:Envelope>");
        return sb.toString();
    }


}
